package com.xjj.sso.server.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xjj.sso.server.SSOConstants;
import com.xjj.sso.server.filter.impl.SSOJsonpHandler;
import com.xjj.sso.server.filter.impl.SSOWebHandler;

public class SSOFilter implements Filter {

	/**	
	 * sso单点登陆分发器
	 */
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		SSOHandler ssoHandler = null;
		
		String jsonp = request.getParameter(SSOConstants.JSONP);
		if(null != jsonp && SSOConstants.JSONP.equals(jsonp))
		{
			ssoHandler = SSOJsonpHandler.getSSOHandler();
		}else
		{
			ssoHandler = SSOWebHandler.getSSOHandler();
		}
		
		
        //访问受保护资源，sso验证
		if(request.getRequestURI().endsWith(SSOConstants.SSO_PATH_AUTHENTICATION))
		{
			ssoHandler.authentication(request, response, chain);
			return;
		}
		//sso登陆
		else if(request.getRequestURI().endsWith(SSOConstants.SSO_PATH_SIGNIN))
		{
			ssoHandler.signin(request, response, chain);
			return;
		}
		
		//sso单点退出
		else if(request.getRequestURI().endsWith(SSOConstants.SSO_PATH_SIGNOUT))
		{
			ssoHandler.signout(request, response, chain);
			return;
		}
	
		
		//sso的ticket的验证
		else if(request.getRequestURI().endsWith(SSOConstants.SSO_PATH_VALIDATETICKET))
		{
			ssoHandler.validateTicket(request, response, chain);
			return;
		}
		
		chain.doFilter(req, resp);
	}
	
	/**
	 * 过滤器初始化，把config.properties里的配置项初始化
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}
	
	public void destroy() {
	}
}